#include "fxcc/core/graph/directX11/UploadBuffer.h"
#include "fxcc/core/graph/directX11/RenderStates.h"

using namespace fxcc::graph::directX11;

fxcc::graph::directX11::UploadBuffer::UploadBuffer(const int sz)
    :m_DataSize(sz)
{
    if (!Init())
    {
        ztclog::info("failed init upload buffer");
   }
}

bool fxcc::graph::directX11::UploadBuffer::Init()
{
    auto device = directX11::RenderStates::Inst().Device();

    HRESULT hr;

    D3D11_BUFFER_DESC bd = {};
    bd.Usage = D3D11_USAGE_DYNAMIC;
    bd.ByteWidth = m_DataSize;
    bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

    hr = device->CreateBuffer(&bd, nullptr, m_ConstantBuffer.GetAddressOf());
    if (FAILED(hr))
        return false;

    return true;
}


void UploadBuffer::VSSet(int startSlot, int num )
{
    auto context = directX11::RenderStates::Inst().Context();
    context->VSSetConstantBuffers(startSlot, num, m_ConstantBuffer.GetAddressOf());

}

void UploadBuffer::PSSet(int startSlot, int num )
{
    auto context = directX11::RenderStates::Inst().Context();
    context->PSSetConstantBuffers(startSlot, num, m_ConstantBuffer.GetAddressOf());

}


void fxcc::graph::directX11::UploadBuffer::Upload(const void* t, const size_t& sz)
{
    auto context = directX11::RenderStates::Inst().Context();

    D3D11_MAPPED_SUBRESOURCE mappedData;
    context->Map(m_ConstantBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedData);
    memcpy_s(mappedData.pData, sz, t, sz);
    context->Unmap(m_ConstantBuffer.Get(), 0);
}